﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.Configuration;
using Funq;
using ServiceStack.Logging;
using g42.Repos;

namespace g42.ServiceProvider
{
  public class ServProv
  {
    string ListeningOn;
    StarterTemplateAppListenerHost appHost;
    ILog log;
    // Funq.Container DIContainer;

    public ServProv()
    {
      // DIContainer = new Funq.Container();
      log = LogManager.GetLogger(GetType());
      ListeningOn = ConfigUtils.GetAppSetting("ListeningOn");
    }

    public void Start(bool SchemaRebuild)
    {
      // ToDo: Sessinfactorie in funq ???
      // Zuerst erstellen, wird auch in appHost.Config gebraucht
      // wenn das nicht klappt fiegen wir raus
      db.sessionFactory = db.CreateSessionFactory(SchemaRebuild);

      if (appHost == null)
      {
        try
        {
          appHost = new StarterTemplateAppListenerHost();// AppHost();
          appHost.Init();
        }
        catch (Exception E)
        {
          log.Error("Could not create AppHost: " + E.Message + Environment.NewLine + E.InnerException);
        }
      }


      try
      {
        appHost.Stop();
        appHost.Start(ListeningOn);
        log.Info("serviceprovider started, listening on: " + ListeningOn);
      }
      catch (Exception E)
      {
        log.Error("Could not start AppHost: " + E.Message + Environment.NewLine + E.InnerException);
      }
    }

    public void Stop()
    {
      if (appHost != null)
      {
        appHost.Stop();
        appHost.Dispose();  // ToDo: ist das ok? Freigabe erzwingen unter .net?
        appHost = null;
      }
    }

  }

}
